<template>
  <div>
    <div style="display: flex;justify-content: flex-end;margin: 10px 0">
      <a href="http://localhost:8088//student/downLoadTemplates" style="margin-right: 30px">
        <el-button size="small" type="primary">下载模板</el-button>
      </a>
      <el-button size="small" type="primary" style="margin-right: 70px" @click="importExcel">导入</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column fixed prop="name" label="姓名" min-width="100" align="center"></el-table-column>
      <el-table-column prop="sex" label="性别" min-width="100" align="center"></el-table-column>
      <el-table-column prop="age" label="年龄" min-width="100" align="center"></el-table-column>
      <el-table-column prop="code" label="学号" min-width="100" align="center"></el-table-column>
      <el-table-column prop="address" label="通讯地址" min-width="100" align="center"></el-table-column>
    </el-table>

    <el-dialog title="学生导入" :visible.sync="dialog" width="600px" @close="closeDialog">
      <el-upload class="upload-demo" ref="upload" action="localhost:8088/student/excelImport"
                 :file-list="fileList" :auto-upload="false" :on-change="handleChange" :limit="1">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <div slot="footer" class="dialog-footer" style="margin-right: 50px">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

export default {
  name: "Student",
  data() {
    return {
      dialog: false,
      tableData: [],
      fileList: [],
    }
  },
  methods: {
    submit() {
      let formData = new FormData();
      formData.append('file', this.fileList[0].raw);
      this.$axios.post('/student/excelImport', formData).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.data;
          this.closeDialog();
        }
      });
    },
    handleChange(file, fileList) {
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (fileType === 'xlsx' || fileType === 'xls') {
        this.fileList = fileList;
      } else {
        fileList.splice(fileList.length - 1)
        this.$message({message: '文件格式不支持!', type: 'warning'});
      }
    },
    importExcel() {
      this.dialog = true;
    },
    closeDialog() {
      this.fileList = [];
      this.dialog = false;
    }
  }
}
</script>
